package com.ck567.springbootnettyprotobufjava.utils;

import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;

/**
 * @description: IPUtils
 */
@Component
public class IPUtils {

    private static String IP_ADDRESS = "";

    /**
     * @return ip
     * @description: 获取本机ip
     */
    public static String getLocalIP() throws SocketException {
        if (StringUtils.isEmpty(IP_ADDRESS)) {
            Set<String> ips = getIPs();
            Optional<String> result = ips.stream().findFirst();
            IP_ADDRESS = result.orElse("127.0.0.1");
        }
        return IP_ADDRESS;
    }


    private static Set<String> getIPs() throws SocketException {
        Set<String> ips = new HashSet<>();
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
            NetworkInterface networkInterface = en.nextElement();
            String name = networkInterface.getName();
            if (!name.contains("docker") && !name.contains("lo")) {
                for (Enumeration<InetAddress> enumIpAddr = networkInterface.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()) {
                        String ipaddress = inetAddress.getHostAddress();
                        if (!ipaddress.contains("::") && !ipaddress.contains("0:0:") && !ipaddress.contains("fe80")) {
                            ips.add(ipaddress);
                        }
                    }
                }
            }
        }
        return ips;
    }
}
